<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>会员信息管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
    /* 修正基础样式 */
    * {
        box-sizing: border-box;
        margin: 0;
        padding: 0;
    }

    body {
        font-family: 'Segoe UI', system-ui, sans-serif;
        line-height: 1.6;
        color: #334155;
        background-color: white;  /* 统一背景为白色 */
        font-size: 16px;
    }

    /* 主容器调整 */
    .module-section {
        max-width: 1200px;
        margin: 0 auto;
        display: grid;
        gap: 2rem;
        padding: 2rem;  /* 移入容器内边距 */
    }

    /* 卡片宽度修正 */
    .card {
        background: white;
        border-radius: 1.5rem;
        padding: 2rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        transition: transform 0.2s;
        width: 100%;  /* 确保占满容器 */
    }

    .card:hover {
        transform: translateY(-2px);
    }

    .module-title {
        font-size: 1.5rem;
        color: #1e293b;
        margin-bottom: 1.5rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .module-title i {
        color: #7c3aed;
        font-size: 1.8rem;
    }

    /* 表单布局优化 */
    .multi-column-form {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 1.5rem;
    }

    .form-group {
        margin-bottom: 1rem;
    }

    .form-group label {
        display: block;
        font-weight: 500;
        margin-bottom: 0.5rem;
        color: #475569;
        font-size: 0.95rem;
    }

    .form-group input,
    .form-group select,
    .form-group textarea {
        width: 100%;
        padding: 0.8rem;
        border: 2px solid #e2e8f0;
        border-radius: 0.75rem;
        font-size: 1rem;
        transition: border-color 0.2s;
    }

    .form-group input:focus,
    .form-group select:focus,
    .form-group textarea:focus {
        outline: none;
        border-color: #7c3aed;
        box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
    }

    .form-group textarea {
        resize: vertical;
        min-height: 100px;
    }

    /* 必填项标识修正 */
    .member-form .form-group label::after {
        content: "*";
        color: #ef4444;
        margin-left: 0.3rem;
    }

    /* 单选按钮组 */
    .radio-group {
        display: flex;
        gap: 1.5rem;
        padding: 0.5rem 0;
    }

    .radio-item {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    input[type="radio"] {
        width: 1.1rem;
        height: 1.1rem;
        accent-color: #7c3aed;
    }

    /* 提交按钮 */
    .submit-btn {
        background: #7c3aed;
        color: white;
        padding: 0.9rem 1.5rem;
        border: none;
        border-radius: 0.75rem;
        font-weight: 500;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        transition: background 0.2s;
    }

    .submit-btn:hover {
        background: #6d28d9;
    }

    /* 会员卡样式 */
    .membership-card {
        background: linear-gradient(135deg, #8b5cf6 0%, #6d28d9 100%);
        color: white;
        border-radius: 1.5rem;
        padding: 2rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        position: relative;
        overflow: hidden;
        width: 100%;  /* 宽度修正 */
    }

    .membership-card::after {
        content: "";
        position: absolute;
        top: -50px;
        right: -30px;
        width: 120px;
        height: 120px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 50%;
    }

    .card-number {
        font-family: monospace;
        letter-spacing: 0.2rem;
        font-size: 1.8rem;
        margin: 1.5rem 0;
        font-weight: 600;
    }

    .card-footer {
        display: flex;
        justify-content: space-between;
        margin-top: 2rem;
        font-size: 1.1rem;
    }

    /* 数据表格 */
    .data-table {
        width: 100%;
        border-collapse: collapse;  /* 修正拼写错误 */
        margin-top: 1rem;
    }

    .data-table th,
    .data-table td {
        padding: 1rem;
        text-align: left;
        border-bottom: 1px solid #e2e8f0;
    }

    .data-table th {
        background: #f8fafc;
        font-weight: 600;
        color: #475569;
    }

    .data-table tr:hover {
        background: #f8fafc;
    }

    /* 状态标签 */
    .status-badge {
        display: inline-block;
        padding: 0.3rem 0.8rem;
        border-radius: 999px;
        font-size: 0.9rem;
        font-weight: 500;
    }

    .status-active {
        background: #dcfce7;
        color: #15803d;
    }

    /* 操作按钮 */
    .item-actions {
        display: flex;
        gap: 0.5rem;
    }

    .btn-small {
        padding: 0.5rem;
        border: none;
        background: transparent;
        color: #64748b;
        cursor: pointer;
        border-radius: 0.5rem;
        transition: all 0.2s;
    }

    .btn-small:hover {
        background: #f1f5f9;
        color: #475569;
    }
    
    /* 编辑和删除按钮样式增强 */
    button[data-action="edit"] {
        color: #3b82f6;
    }
    
    button[data-action="edit"]:hover {
        background-color: #dbeafe;
        color: #1d4ed8;
    }
    
    button[data-action="delete"] {
        color: #ef4444;
    }
    
    button[data-action="delete"]:hover {
        background-color: #fee2e2;
        color: #b91c1c;
    }

    /* 提示信息 */
    .alert {
        padding: 1rem 1.5rem;
        border-radius: 0.75rem;
        margin-bottom: 1.5rem;
        display: none;
        font-weight: bold;
        position: relative;
        z-index: 100;
    }

    .alert-success {
        background-color: #dcfce7;
        color: #15803d;
        border-left: 4px solid #15803d;
    }

    .alert-error {
        background-color: #fee2e2;
        color: #b91c1c;
        border-left: 4px solid #b91c1c;
    }

    /* 响应式布局 */
    @media (max-width: 768px) {
        .module-section {
            padding: 1rem;  /* 移动端内边距调整 */
        }

        .card {
            padding: 1.5rem;
        }

        .card-number {
            font-size: 1.4rem;
        }
    }
    
    /* 淡出动画效果 */
    @keyframes fadeOut {
        from { opacity: 1; }
        to { opacity: 0; }
    }
    
    /* 淡入动画效果 */
    @keyframes fadeIn {
        from { opacity: 0; background-color: #e0f2fe; }
        to { opacity: 1; background-color: transparent; }
    }
    </style>
</head>
<body>
    <div class="module-section">
        <!-- 会员信息录入卡片 -->
        <div class="card">
            <h2 class="module-title">
                <i class="fas fa-user-plus"></i>
                会员信息录入
            </h2>

            <div id="alertMessage" class="alert"></div>

            <form id="memberForm" class="multi-column-form" onsubmit="return false;">
                <div class="form-group">
                    <label>会员姓名</label>
                    <input type="text" id="memberName" placeholder="请输入会员姓名" required>
                </div>
                <div class="form-group">
                    <label>性别</label>
                    <div class="radio-group">
                        <label class="radio-item"><input type="radio" name="gender" value="1" checked> 男</label>
                        <label class="radio-item"><input type="radio" name="gender" value="0"> 女</label>
                    </div>
                </div>
                <div class="form-group">
                    <label>手机号码</label>
                    <input type="tel" id="memberPhone" pattern="[0-9]{11}" placeholder="请输入11位手机号" required>
                </div>
                <div class="form-group">
                    <label>会员积分</label>
                    <input type="number" id="memberPoints" value="0" readonly>
                </div>
                <div class="form-group">
                    <button type="button" id="saveBtn" class="submit-btn"><i class="fas fa-save"></i> 保存会员</button>
                    <button type="button" id="resetFormBtn" class="submit-btn" style="background:#64748b; margin-left:10px; display:none"><i class="fas fa-times"></i> 取消</button>
                </div>
            </form>
        </div>

        <!-- 会员列表 -->
        <div class="card">
            <h2 class="module-title">
                <i class="fas fa-users"></i>
                会员信息列表
                <span id="memberCountBadge" style="font-size: 0.8rem; background: #e0e7ff; color: #4f46e5; padding: 0.2rem 0.5rem; border-radius: 999px; margin-left: 0.5rem;">
                    0 位会员
                </span>
            </h2>

            <table class="data-table">
                <thead>
                    <tr>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>手机号</th>
                        <th>积分</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="memberTableBody">
                    <!-- 会员数据将通过JavaScript动态加载 -->
                </tbody>
            </table>
        </div>
    </div>

    <script>
        (function(){
            // stub log function to suppress debug calls
            function log(message, type) {}
            // 获取DOM元素
            const memberForm = document.getElementById('memberForm');
            const alertMessage = document.getElementById('alertMessage');
            const memberTableBody = document.getElementById('memberTableBody');
            const resetFormBtn = document.getElementById('resetFormBtn');
            const saveBtn = document.getElementById('saveBtn');
            const memberCountBadge = document.getElementById('memberCountBadge');
            
            console.log("会员管理脚本已加载");
            
            // 重置按钮点击事件
            resetFormBtn.addEventListener('click', function() {
                resetFormToAddMode();
            });
            
            // 重置表单到添加模式
            function resetFormToAddMode() {
                memberForm.reset();
                
                // 移除隐藏的会员ID字段
                const hiddenMemberId = document.getElementById('hiddenMemberId');
                if (hiddenMemberId) {
                    hiddenMemberId.remove();
                }
                
                // 重置积分
                document.getElementById('memberPoints').value = 0;
                
                // 恢复提交按钮文本
                const submitBtn = memberForm.querySelector('.submit-btn');
                submitBtn.innerHTML = '<i class="fas fa-save"></i> 保存会员';
                
                // 隐藏重置按钮
                resetFormBtn.style.display = 'none';
                
                // 显示成功提示
                showAlert('已取消编辑，可以添加新会员', 'success');
            }
            
            // 加载会员列表
            loadMembers();
            
            // 保存按钮点击事件
            saveBtn.addEventListener('click', function() {
                log("保存按钮点击，正在处理...");
                
                // 获取表单数据并验证
                const nameEl = document.getElementById('memberName');
                const phoneEl = document.getElementById('memberPhone');
                
                // 验证必填字段
                if (!nameEl.value.trim()) {
                    showAlert('请输入会员姓名', 'error');
                    log("验证失败：姓名为空", "error");
                    nameEl.focus();
                    return;
                }
                
                if (!phoneEl.value.trim()) {
                    showAlert('请输入手机号码', 'error');
                    log("验证失败：手机号为空", "error");
                    phoneEl.focus();
                    return;
                }
                
                // 验证手机号格式
                if (!/^1\d{10}$/.test(phoneEl.value.trim())) {
                    showAlert('请输入正确的11位手机号码', 'error');
                    log("验证失败：手机号格式不正确", "error");
                    phoneEl.focus();
                    return;
                }
                
                // 禁用提交按钮，防止重复提交
                const originalBtnText = saveBtn.innerHTML;
                saveBtn.disabled = true;
                saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
                
                // 构建数据对象
                const memberData = {
                    name: nameEl.value.trim(),
                    gender: document.querySelector('input[name="gender"]:checked').value,
                    phone: phoneEl.value.trim()
                };
                
                log("表单数据:", "info");
                log(memberData);
                
                // 检查是新增还是编辑
                const hiddenMemberId = document.getElementById('hiddenMemberId');
                let url = '/api/members';
                let method = 'POST';
                
                if (hiddenMemberId && hiddenMemberId.value) {
                    // 编辑现有会员
                    url = `/api/members/${hiddenMemberId.value}`;
                    method = 'PUT';
                    
                    // 编辑模式下，保留原有积分
                    const pointsEl = document.getElementById('memberPoints');
                    if (pointsEl && pointsEl.value) {
                        memberData.points = parseInt(pointsEl.value, 10);
                    }
                    
                    log("编辑会员ID: " + hiddenMemberId.value);
                } else {
                    log("添加新会员");
                }
                
                // 显示加载提示
                showAlert('正在处理，请稍候...', 'success');
                
                // 添加发送请求前的日志
                log(`准备发送${method}请求到 ${url}`, 'api');
                
                // 发送API请求
                fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify(memberData)
                })
                // 先解析JSON，再根据HTTP状态处理错误
                .then(response => response.json().then(result => {
                    if (!response.ok) {
                        throw new Error(result.message || '网络请求失败: ' + response.status);
                    }
                    return result;
                }))
                .then(result => {
                    // 成功处理
                    showAlert(method === 'POST' ? '会员添加成功' : '会员信息更新成功', 'success');
                    const savedMember = result.data;
                    console.log("保存成功，返回数据:", savedMember);
                    
                    if (method === 'POST') {
                        addMemberToTable(savedMember);
                    } else {
                        updateMemberInTable(savedMember);
                    }
                    resetFormToAddMode();
                })
                .catch(error => {
                    // 展示后端或网络错误信息
                    showAlert(error.message, 'error');
                })
                .finally(() => {
                    // 恢复按钮状态
                    saveBtn.disabled = false;
                    saveBtn.innerHTML = originalBtnText;
                });
            });
            
            // 测试数据填充
            const initDataBtn = document.getElementById('initDataBtn');
            initDataBtn.addEventListener('click', function() {
                log("填充测试数据");
                
                // 随机选择一个名字
                const names = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];
                const randomName = names[Math.floor(Math.random() * names.length)];
                
                // 随机生成一个手机号
                const phonePrefix = ['138', '139', '137', '136', '135', '186', '187', '188'];
                const randomPhone = phonePrefix[Math.floor(Math.random() * phonePrefix.length)] + 
                                   Math.floor(Math.random() * 100000000).toString().padStart(8, '0');
                
                // 随机生成出生日期（1970-2000年间）
                const startYear = 1970;
                const endYear = 2000;
                const randomYear = startYear + Math.floor(Math.random() * (endYear - startYear + 1));
                const randomMonth = (Math.floor(Math.random() * 12) + 1).toString().padStart(2, '0');
                const randomDay = (Math.floor(Math.random() * 28) + 1).toString().padStart(2, '0');
                const randomBirthDate = `${randomYear}-${randomMonth}-${randomDay}`;
                
                // 随机选择性别
                const randomGender = Math.random() > 0.5 ? '1' : '0';
                
                // 随机选择会员等级
                const randomLevel = (Math.floor(Math.random() * 4) + 1).toString();
                
                // 填充表单
                document.getElementById('memberName').value = randomName;
                document.querySelector(`input[name="gender"][value="${randomGender}"]`).checked = true;
                document.getElementById('memberPhone').value = randomPhone;
                document.getElementById('memberBirthDate').value = randomBirthDate;
                document.getElementById('memberLevel').value = randomLevel;
                document.getElementById('memberAddress').value = '北京市朝阳区xxx路xxx号';
                document.getElementById('memberNotes').value = '这是一条测试备注信息';
                
                // 更新会员等级预览
                const levelSelect = document.getElementById('memberLevel');
                const levelText = levelSelect.options[levelSelect.selectedIndex].text;
                document.getElementById('previewMemberLevel').textContent = levelText;
                
                // 自动生成卡号
                const cardNumber = '6217' + Math.random().toString().substring(2, 16);
                previewCardNumber.textContent = formatCardNumber(cardNumber);
                
                // 创建一个隐藏字段存储实际卡号
                let cardNumberInput = document.getElementById('hiddenCardNumber');
                if (!cardNumberInput) {
                    cardNumberInput = document.createElement('input');
                    cardNumberInput.type = 'hidden';
                    cardNumberInput.id = 'hiddenCardNumber';
                    cardNumberInput.name = 'card_number';
                    memberForm.appendChild(cardNumberInput);
                }
                cardNumberInput.value = cardNumber;
                
                log("测试数据已填充", "success");
                showAlert('测试数据已填充，可以直接点击保存', 'success');
            });
            
            // 将会员直接添加到表格
            function addMemberToTable(member) {
                console.log("正在将会员直接添加到表格:", member);
                
                // 检查表格是否为空，如果是空的需要清除"暂无数据"的提示行
                if (memberTableBody.querySelector('td[colspan="7"]')) {
                    memberTableBody.innerHTML = '';
                }
                
                const row = document.createElement('tr');
                row.setAttribute('data-id', member.member_code);
                row.style.animation = 'fadeIn 0.5s';
                
                // 格式化手机号，中间4位用星号代替
                const maskedPhone = member.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
                
                // 格式化余额，保留两位小数，加上千位分隔符
                const formattedPoints = member.points;
                
                row.innerHTML = `
                    <td>${member.name}</td>
                    <td>${member.gender == 1 ? '男' : '女'}</td>
                    <td>${maskedPhone}</td>
                    <td>${formattedPoints}</td>
                    <td>
                        <div class="item-actions">
                            <button class="btn-small" data-action="edit" data-id="${member.member_code}" title="编辑">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn-small" data-action="delete" data-id="${member.member_code}" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                `;
                
                // 添加到表格的最前面
                if (memberTableBody.firstChild) {
                    memberTableBody.insertBefore(row, memberTableBody.firstChild);
                } else {
                    memberTableBody.appendChild(row);
                }
                
                // 添加事件监听
                const editBtn = row.querySelector('button[data-action="edit"]');
                editBtn.addEventListener('click', function() {
                    const memberId = this.getAttribute('data-id');
                    console.log("点击编辑按钮，会员ID:", memberId);
                    loadMemberForEdit(memberId);
                });
                
                const deleteBtn = row.querySelector('button[data-action="delete"]');
                deleteBtn.addEventListener('click', function() {
                    const memberId = this.getAttribute('data-id');
                    console.log("点击删除按钮，会员ID:", memberId);
                    if (confirm('确定要删除该会员吗？此操作不可撤销。')) {
                        deleteMember(memberId);
                    }
                });
                
                // 滚动到新添加的行
                row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                
                // 更新会员数徽章
                const total = memberTableBody.querySelectorAll('tr').length;
                memberCountBadge.textContent = total + ' 位会员';
            }
            
            // 显示提示信息
            function showAlert(message, type) {
                console.log("显示提示:", message, type);
                alertMessage.textContent = message;
                alertMessage.className = 'alert alert-' + type;
                alertMessage.style.display = 'block';
                
                // 5秒后自动隐藏
                setTimeout(() => {
                    alertMessage.style.display = 'none';
                }, 5000);
            }
            
            // 加载会员列表
            function loadMembers() {
                console.log("正在加载会员列表...");
                memberTableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;"><i class="fas fa-spinner fa-spin"></i> 加载会员数据中...</td></tr>';
                const timestamp = new Date().getTime();
                fetch(`/api/members?_=${timestamp}`, {
                    headers: {
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0'
                    }
                })
                .then(response => {
                    if (!response.ok) throw new Error('网络请求失败: ' + response.status);
                    return response.json();
                })
                .then(result => {
                    if (!result.success) throw new Error(result.message || '获取会员数据失败');
                    const members = result.data;
                    console.log("获取到会员数据:", members.length, "条记录");
                    
                    // 输出第一条会员数据用于调试
                    if(members && members.length > 0) {
                        console.log("第一条会员数据:", JSON.stringify(members[0]));
                    }
                    
                    memberTableBody.innerHTML = '';
                    if (!members || members.length === 0) {
                        const emptyRow = document.createElement('tr');
                        emptyRow.innerHTML = '<td colspan="7" style="text-align: center;">暂无会员数据</td>';
                        memberTableBody.appendChild(emptyRow);
                        memberCountBadge.textContent = '0 位会员';
                        return;
                    }
                    members.forEach(member => {
                        const row = document.createElement('tr');
                        row.setAttribute('data-id', member.member_code);
                        
                        // 格式化手机号，中间4位用星号代替
                        const maskedPhone = member.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
                        
                        // 格式化余额，保留两位小数，加上千位分隔符
                        const formattedPoints = member.points;
                        
                        row.innerHTML = `
                            <td>${member.name}</td>
                            <td>${member.gender == 1 ? '男' : '女'}</td>
                            <td>${maskedPhone}</td>
                            <td>${formattedPoints}</td>
                            <td>
                                <div class="item-actions">
                                    <button class="btn-small" data-action="edit" data-id="${member.member_code}" title="编辑">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <button class="btn-small" data-action="delete" data-id="${member.member_code}" title="删除">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        `;
                        
                        memberTableBody.appendChild(row);
                    });
                    addActionButtonListeners();
                    memberCountBadge.textContent = members.length + ' 位会员';
                })
                .catch(error => {
                    console.error('加载会员列表错误:', error);
                    showAlert('加载会员列表失败: ' + error.message, 'error');
                    memberTableBody.innerHTML = '';
                    const errorRow = document.createElement('tr');
                    errorRow.innerHTML = `<td colspan="7" style="text-align: center; color: #b91c1c;">加载失败: ${error.message}，请刷新页面重试</td>`;
                    memberTableBody.appendChild(errorRow);
                    memberCountBadge.textContent = '0 位会员';
                });
            }
            
            // 格式化会员卡号，每4位一组，用空格分隔
            function formatCardNumber(cardNumber) {
                if (!cardNumber) return '----';
                return cardNumber.replace(/(\d{4})(?=\d)/g, '$1 ');
            }
            
            // 添加操作按钮事件监听
            function addActionButtonListeners() {
                console.log("添加按钮事件监听");
                // 编辑按钮
                document.querySelectorAll('button[data-action="edit"]').forEach(button => {
                    button.addEventListener('click', function() {
                        const memberId = this.getAttribute('data-id');
                        console.log("点击编辑按钮，会员ID:", memberId);
                        loadMemberForEdit(memberId);
                    });
                });
                
                // 删除按钮
                document.querySelectorAll('button[data-action="delete"]').forEach(button => {
                    button.addEventListener('click', function() {
                        const memberId = this.getAttribute('data-id');
                        console.log("点击删除按钮，会员ID:", memberId);
                        if (confirm('确定要删除该会员吗？此操作不可撤销。')) {
                            deleteMember(memberId);
                        }
                    });
                });
            }
            
            // 删除会员
            function deleteMember(memberId) {
                console.log("正在删除会员...", memberId);
                showAlert('正在删除...', 'success');
                
                // 删除前先禁用所有删除按钮，防止重复点击
                document.querySelectorAll('button[data-action="delete"]').forEach(btn => {
                    btn.disabled = true;
                    btn.style.opacity = "0.5";
                });
                
                // 对要删除的行添加视觉效果
                const row = document.querySelector(`button[data-action="delete"][data-id="${memberId}"]`).closest('tr');
                row.style.backgroundColor = "#fee2e2";
                row.style.opacity = "0.7";
                
                fetch(`/api/members/${memberId}`, {
                    method: 'DELETE',
                    headers: {
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache',
                        'Expires': '0'
                    }
                })
                .then(response => {
                    console.log("删除请求状态:", response.status, response.statusText);
                    if (!response.ok) {
                        throw new Error('网络请求失败: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("删除响应:", data);
                    if (!data.success) {
                        showAlert(data.message || '删除失败', 'error');
                        // 恢复行样式
                        row.style.backgroundColor = "";
                        row.style.opacity = "";
                    } else {
                        showAlert('会员删除成功', 'success');
                        
                        // 从DOM中直接移除该行，不用重新加载整个列表
                        row.style.animation = "fadeOut 0.5s";
                        setTimeout(() => {
                            row.remove();
                            
                            // 检查表格是否为空
                            if (memberTableBody.children.length === 0) {
                                const emptyRow = document.createElement('tr');
                                emptyRow.innerHTML = '<td colspan="7" style="text-align: center;">暂无会员数据</td>';
                                memberTableBody.appendChild(emptyRow);
                            }
                        }, 500);
                    }
                    
                    // 恢复所有删除按钮
                    document.querySelectorAll('button[data-action="delete"]').forEach(btn => {
                        btn.disabled = false;
                        btn.style.opacity = "";
                    });
                })
                .catch(error => {
                    console.error('删除会员错误:', error);
                    showAlert('删除失败: ' + error.message, 'error');
                    
                    // 恢复行样式
                    row.style.backgroundColor = "";
                    row.style.opacity = "";
                    
                    // 恢复所有删除按钮
                    document.querySelectorAll('button[data-action="delete"]').forEach(btn => {
                        btn.disabled = false;
                        btn.style.opacity = "";
                    });
                });
            }
            
            // 加载会员数据用于编辑
            function loadMemberForEdit(memberId) {
                console.log("正在加载会员数据进行编辑...", memberId);
                showAlert('正在加载会员信息...', 'success');
                
                fetch(`/api/members/${memberId}`)
                .then(response => {
                    if (!response.ok) throw new Error('网络请求失败: ' + response.status);
                    return response.json();
                })
                .then(result => {
                    if (!result.success) throw new Error(result.message || '加载会员信息失败');
                    const member = result.data;
                    console.log("获取到会员数据:", member);
                    document.getElementById('memberName').value = member.name;
                    document.querySelector(`input[name="gender"][value="${member.gender}"]`).checked = true;
                    document.getElementById('memberPhone').value = member.phone;
                    document.getElementById('memberPoints').value = member.points;
                    
                    // 添加会员ID到隐藏字段
                    let memberIdInput = document.getElementById('hiddenMemberId');
                    if (!memberIdInput) {
                        memberIdInput = document.createElement('input');
                        memberIdInput.type = 'hidden';
                        memberIdInput.id = 'hiddenMemberId';
                        memberIdInput.name = 'member_id';
                        memberForm.appendChild(memberIdInput);
                    }
                    memberIdInput.value = member.member_code;
                    
                    // 不要重置积分，保留原始积分
                    // document.getElementById('memberPoints').value = 0;
                    
                    // 显示重置按钮
                    resetFormBtn.style.display = 'inline-flex';
                    
                    // 滚动到表单顶部
                    memberForm.scrollIntoView({ behavior: 'smooth' });
                    
                    showAlert('会员信息已加载，可以进行编辑', 'success');
                })
                .catch(error => {
                    console.error('加载会员错误:', error);
                    showAlert('加载会员信息失败: ' + error.message, 'error');
                });
            }
            
            // 会员等级字段变化时，更新预览卡片
            document.getElementById('memberLevel').addEventListener('change', function() {
                const levelSelect = this;
                const levelText = levelSelect.options[levelSelect.selectedIndex].text;
                document.getElementById('previewMemberLevel').textContent = levelText;
            });
            
            // 更新表格中的会员信息
            function updateMemberInTable(member) {
                log("正在更新表格中的会员信息:", member);
                
                // 查找表格中对应的行
                const row = memberTableBody.querySelector(`tr[data-id="${member.member_code}"]`);
                if (!row) {
                    log("未找到对应的会员行，将添加为新行", "warning");
                    // 如果没找到对应行，则添加为新行
                    addMemberToTable(member);
                    return;
                }
                
                // 格式化手机号，中间4位用星号代替
                const maskedPhone = member.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
                
                // 格式化余额，保留两位小数，加上千位分隔符
                const formattedPoints = member.points;
                
                // 高亮动画效果
                row.style.animation = '';
                setTimeout(() => {
                    row.style.animation = 'fadeIn 0.5s';
                }, 10);
                
                // 更新行内容
                row.innerHTML = `
                    <td>${member.name}</td>
                    <td>${member.gender == 1 ? '男' : '女'}</td>
                    <td>${maskedPhone}</td>
                    <td>${formattedPoints}</td>
                    <td>
                        <div class="item-actions">
                            <button class="btn-small" data-action="edit" data-id="${member.member_code}" title="编辑">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn-small" data-action="delete" data-id="${member.member_code}" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                `;
                
                // 重新添加事件监听
                const editBtn = row.querySelector('button[data-action="edit"]');
                editBtn.addEventListener('click', function() {
                    const memberId = this.getAttribute('data-id');
                    log("点击编辑按钮，会员ID:", memberId);
                    loadMemberForEdit(memberId);
                });
                
                const deleteBtn = row.querySelector('button[data-action="delete"]');
                deleteBtn.addEventListener('click', function() {
                    const memberId = this.getAttribute('data-id');
                    log("点击删除按钮，会员ID:", memberId);
                    if (confirm('确定要删除该会员吗？此操作不可撤销。')) {
                        deleteMember(memberId);
                    }
                });
                
                // 滚动到此行
                row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                
                log("会员信息更新成功", "success");
            }
            
            console.log("会员管理脚本初始化完成");
        })();
    </script>
</body>
</html>